package com.melo;

/**
 * @author lichunlong lcl253137@alibaba-inc.com
 * @desc 字符串匹配: 暴力匹配
 * @date 2025-04-27
 */
public class ViolenceMatch {

    /**
     * 字符串暴力匹配
     *
     * @param source 源字符串: 被匹配的字符串
     * @param dest   目标字符串: 匹配的字符串
     * @return 匹配到的字符串的位置, 没有匹配到返回-1
     */
    public static int violenceMatch(String source, String dest) {
        char[] sourceCharArr = source.toCharArray();
        char[] destCharArr = dest.toCharArray();

        int sourceSearchIndex = 0;
        int destSearchIndex = 0;

        while (sourceSearchIndex < sourceCharArr.length && destSearchIndex < destCharArr.length) {
            if (sourceCharArr[sourceSearchIndex] == destCharArr[destSearchIndex]) {
                sourceSearchIndex++;
                destSearchIndex++;
            } else {
                sourceSearchIndex = sourceSearchIndex - (destSearchIndex - 1);
                destSearchIndex = 0;
            }
        }

        return destSearchIndex == destCharArr.length ? sourceSearchIndex - destSearchIndex : -1;
    }
}
